import 'package:flutter/material.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

const int defaultPage = 1;
const int defaultPageSize = 20;

mixin VolvoRefreshMixin<T> {

  RefreshController refreshController = RefreshController(initialRefresh: false);

  /// 自动刷新控制器
  void initAutoRefreshController() {
    refreshController = RefreshController(initialRefresh: true);
  }

  ///接口返回的数据
  List<T> dataList = [];

  /// 当前页
  int _currentPage = defaultPage;

  /// 每页请求数
  int pageSize = defaultPageSize;

  /// 判断是否还有数据
  bool hasNext = false;

  /// 接口方法
  Future<List<T>> requestList(int page);

  ///用于在数据加载完成后的操作
  void onRequestComplete() {}

  /// 初始化当前页面
  int initPage() {
    return defaultPage;
  }

  /// 下拉刷新
  Future onRefresh() async {
    try {
      _currentPage = initPage();
      List<T> list = await requestList(_currentPage);
      if (list.isNotEmpty) {
        dataList.clear();
        dataList.addAll(list);
        onRequestComplete();
      }
      refreshController.refreshCompleted(resetFooterState: true);
      if (hasNext) {
        debugPrint("onRefresh有数据");
        refreshController.resetNoData();
      } else {
        debugPrint("onRefresh没有数据");
        refreshController.loadNoData();
      }
    } catch (e) {
      debugPrint("onRefreshError:$e");
    }
  }

  /// 上拉加载
  Future onLoading() async {
    try {
      _currentPage++;
      List<T> list = await requestList(_currentPage);
      if (list.isNotEmpty) {
        dataList.addAll(list);
        onRequestComplete();
      } else {
        subtractPage();
      }
      refreshController.loadComplete();

      if (hasNext) {
        debugPrint("onLoading有数据");
        refreshController.resetNoData();
      } else {
        debugPrint("onLoading没有数据");
        refreshController.loadNoData();
      }
    } catch (e) {
      subtractPage();
      debugPrint("onLoadingError:$e");
    }
  }

  void subtractPage() {
    if (_currentPage > initPage()) {
      _currentPage--;
    }
  }

  void callRefresh() {
    refreshController.requestRefresh(
      duration: const Duration(milliseconds: 250),
    );
  }
}
